<script setup lang='ts'>
import { useDictAdd, useDictDel, useDictEdit, useGetDictList } from '@fl/api/man-api/jc-dict'
import { SearchForm, SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { btns, formState, initPage, searchState, statusMap } from './constant'

const router = useRouter()
const { createMessage } = useMessage()

const showDiglog = ref(false)
const tableData = ref<any>([])

// 新增类目表单
const tablePage = ref<any>(cloneDeep(initPage))
const state = ref<any>(cloneDeep(searchState))
const form = ref<any>(cloneDeep(formState))

const gridOptions = reactive<any>({
    columns: [
        { field: 'dictId', title: '字典主键' },
        { field: 'dictName', title: '字典名称' },
        { slots: { default: 'dictType' }, title: '字典类型' },
        { slots: { default: 'status' }, title: '状态' },
        { field: 'remark', title: '备注' },
        { field: 'createTime', title: '创建时间' },
        { slots: { default: 'operate' }, title: '操作', width: 250 },
    ],
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const params = computed(() => ({
    ...state.value,
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))
// 查询内容列表
const { data, isLoading, refetch } = useGetDictList(params)

// 列表查询条件
const searchCol = [
    {
        colProps: {
            span: 8,
        },
        label: '字典名称',
        prop: 'dictName',
    },
    {
        colProps: {
            span: 8,
        },
        label: '字典类型',
        prop: 'dictType',
    },
    {
        colProps: {
            span: 8,
        },
        label: '状态',
        options: statusMap,
        prop: 'status',
        valueType: 'select',
    },
    // {
    //     colProps: {
    //         span: 8,
    //     },
    //     fieldProps: {
    //         endPlaceholder: '结束日期',
    //         format: 'YYYY-MM-DD',
    //         startPlaceholder: '开始日期',
    //         type: 'daterange',
    //     },
    //     label: '创建时间',
    //     prop: 'createTime',
    //     valueType: 'date-picker',
    // },
]

// 新增编辑表单配置
const formCol: any = [
    {
        fieldProps: {
            maxlength: 20,
        },
        label: '字典名称',
        prop: 'dictName',
    },
    {
        fieldProps: {
            maxlength: 50,
        },
        label: '字典类型',
        prop: 'dictType',
        tooltip: '数据存储中的Key值，如：sys_user_sex',
    },
    {
        label: '状态',
        options: statusMap,
        prop: 'status',
        valueType: 'radio',
    },
    {
        label: '备注',
        prop: 'remark',
    },
]
const rules = {
    dictName: [{ message: '请输入字典名称', required: true, trigger: 'blur' }],
    dictType: [{ message: '请输入字典类型', required: true, trigger: 'blur' }],
}

function getData(val: any) {
    state.value = {
        ...val,
    }

    refetch()
}

function reset() {
    state.value = cloneDeep(searchState)
    tablePage.value = cloneDeep(initPage)

    refetch()
}

// 删除富文本内容
const { mutate: mutateDictDel } = useDictDel()

function doAction(item: any, row: any) {
    switch (item.value) {
        case 'list':
            view(row)
            break
        case 'edit':
            form.value = { ...row }
            showDiglog.value = true
            break
        case 'delete':
            mutateDictDel(row.dictId, {
                onSuccess: () => {
                    refetch()
                    createMessage.success('操作成功')
                },
            })
            break
        default:
            break
    }
}

function doAdd() {
    form.value = cloneDeep(formState)

    showDiglog.value = true
}

// 富文本内容 新增 编辑保存接口
const { mutate: mutateAdd } = useDictAdd()
const { mutate: mutateEdit } = useDictEdit()
function doSave() {
    if (form.value?.dictId) {
        mutateEdit(form.value, {
            onSuccess: () => {
                refetch()
                showDiglog.value = false
                createMessage.success('操作成功')
            },
        })
    }
    else {
        mutateAdd(form.value, {
            onSuccess: () => {
                refetch()
                showDiglog.value = false
                createMessage.success('操作成功')
            },
        })
    }
}

function view(row: any) {
    router.push({
        path: '/operations-pages/system-setting/dicts-info',
        query: {
            dictType: row.dictType,
        },
    })
}

watchEffect(() => {
    if (data.value) {
        tableData.value = data.value?.rows ?? []
        tablePage.value.total = data.value.total ?? 0
    }
})
</script>

<template>
    <ElCard shadow="never">
        <SearchForm v-bind="state"
                    :columns="searchCol"
                    submit-text="查询"
                    class="mb-20"
                    @submit="getData"
                    @reset="reset"
        />

        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     v-loading="isLoading"
                     :data="tableData"
        >
            <template #toolbar_buttons>
                <ElButton type="primary"
                          @click="doAdd"
                >
                    新增
                </ElButton>
            </template>

            <template #status="{ row }">
                <span class="px-10 py-2 rounded-20 c-#fff"
                      :class="{ 'bg-#1ab394': row?.status === '0', 'bg-#acb3b1': row?.status === '1' }"
                >
                    {{ statusMap.find((v) => v.value === row.status)?.label ?? row.status }}
                </span>
            </template>

            <template #dictType="{ row }">
                <span class="c-#337ab7 cursor-pointer"
                      @click="view(row)"
                >{{ row.dictType }}</span>
            </template>

            <template #operate="{ row }">
                <ButtonItem :btns="btns"
                            @btn-click="doAction($event, row)"
                />
            </template>
        </SearchTable>
    </ElCard>

    <!-- 字典新增编辑弹框 -->
    <PlusDialogForm v-model:visible="showDiglog"
                    v-model="form"
                    :title="form?.dictId ? '编辑' : '新增'"
                    :form="{ columns: formCol, rules, labelWidth: 100 }"
                    @confirm="doSave"
    />
</template>

<style lang="scss" scoped>
</style>
